// TODO: use dva/fetch after dva@1.2
import fetch from 'dva/fetch';
import { message } from 'antd';

function parseJSON(response) {
  return response.json();
}
function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

export function request(url, options) {
  if (options.method == "GET") {
    if (options.params) {
      let paramsArray = [];
      //拼接参数  
      Object.keys(options.params).forEach(key => paramsArray.push(key + '=' + options.params[key]))
      if (url.search(/\?/) === -1) {
        url += '?' + paramsArray.join('&')
      } else {
        url += '&' + paramsArray.join('&')
      }
      options.params = undefined;
    }
  }
  options.credentials = 'same-origin';
  
  return fetch(`/api/${url}`, options)
    .then(checkStatus)
    .then(parseJSON)
    .then((data) => {
      // 检测到未登录，直接跳转到登录页面.
      if (data.statusCode === 401) {
        var fromUrl = data.data.replace('api/','');
        window.location.href = fromUrl.substr(0,fromUrl.lastIndexOf('/'));
      }
      return { data };
    })
    .catch((err) => {
      message.error(err);
    });
}


export function postOptions(values) {
  const options = {
    method: "POST",
    body: JSON.stringify(values),
    headers: { 'Content-Type': 'application/json' }
  };
  return options;
}
export function getOptions(values) {
  const options = {
    method: "GET",
    params: values,
    headers: { 'Content-Type': 'application/json' }
  };
  return options;
}